package com.czh.proxy;

import com.czh.entity.RpcRequest;
import com.czh.entity.RpcResponse;
import com.czh.utils.IoClient;
import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author chenzhihua
 * @desc 传入参数Service接口的class对象，反射封装成一个request
 * @date 2024/1/9
 * @Version V1.1.0
 */
@AllArgsConstructor
public class ClientProxy implements InvocationHandler {

    private String host;
    private int port;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = RpcRequest.builder().interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .params(args).paramTypes(method.getParameterTypes())
                .build();
        RpcResponse response = IoClient.sendRequest(host, port, rpcRequest);
        return response.getData();
    }

    public <T>T getProxy(Class<T> clazz){
        Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
        return (T)o;
    }
}
